package com.juku2024.juku.viewmodel

import androidx.lifecycle.viewModelScope
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.FavoriteEntity
import com.juku2024.juku.db.entity.HistoryEntity
import com.juku2024.juku.tools.NetworkUtils
import kotlinx.coroutines.*

class HistoryViewModel : BaseViewModel() {

    fun getHistory(success: (history: List<HistoryEntity>) -> Unit, fail: (msg: String) -> Unit){

        viewModelScope.launch {
            try {
                if (NetworkUtils.isWifiProxy()) {
                    fail("为了网络安全，请关闭代理或VPN再使用！")
                    return@launch
                }
                val history = withContext(Dispatchers.Default) {
                    NoteRoomUtils.getInstance().historyDao().queryHistories()
                }
                if (!isActive) return@launch
                if (history.isNullOrEmpty()) {
                    fail("您还没有浏览过视频！")
                }  else {
                    success(history)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                if (!isActive) return@launch
                fail("您还没有浏览过视频！")
            }
        }
    }

    fun getFavorite(success: (history: List<FavoriteEntity>) -> Unit, fail: (msg: String) -> Unit){
        viewModelScope.launch {
            try {
                if (NetworkUtils.isWifiProxy()) {
                    fail("为了网络安全，请关闭代理或VPN再使用！")
                    return@launch
                }
                val favoriteList = withContext(Dispatchers.Default) {
                    NoteRoomUtils.getInstance().favoriteDao().queryFavoriteList()
                }
                if (!isActive) return@launch
                if (favoriteList.isNullOrEmpty()) {
                    fail("您还没有收藏过视频！")
                }  else {
                    success(favoriteList)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                if (!isActive) return@launch
                fail("您还没有收藏过视频！")
            }
        }
    }
}